package com.tiem_files.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * JDBC工具类
 * @author
 */
public class JDBCUtil {

    private static DataSource dataSource;
    static {
        Properties properties = new Properties();
        try {
            ClassLoader loader =JDBCUtil.class.getClassLoader();
            InputStream stream = loader.getResourceAsStream("db.properties");
            properties.load(stream);
            dataSource= DruidDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得数据源
     * @return  dataSource
     */
    public static DataSource getDataSource(){
        return dataSource;
    }

    /**
     * 获得SQL的连接
     * @return Connection
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 关闭连接
     * @param connection 客户端连接
     * @param statement 封装sql处理
     * @param resultSet sql查询结果集
     */
    public static void close(Connection connection,Statement statement, ResultSet resultSet){
       if (null!=connection){
           try {
               connection.close();
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    }
